package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;


/**
 * 全局异常处理器
 * @RestControllerAdvice=@ControllerAdvice+@ResponseBody
 * @ControllerAdvice //全局异常处理器
 * @ResponseBody // 返回json格式数据
 */
@RestControllerAdvice(annotations ={RestController.class, Controller.class} ) //全局异常处理器注解 可以捕获所有异常信息
@Slf4j
public class GlobalExceptionHandler {
    //Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '摸鱼部' for key 'dept.name'
    //; Duplicate entry '摸鱼部' for key 'dept.name'] with root cause
    //异常处理（唯一约束异常）
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result exception(SQLIntegrityConstraintViolationException e){
        log.error("唯一约束异常：{}",e.getMessage());
        if (e.getMessage().contains("Duplicate entry")){
            String[] split = e.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return Result.error(msg);
        }
        return Result.error("未知错误");
    }
    //自定义异常处理
    @ExceptionHandler(CustomException.class)
    public Result exception(CustomException e){
        return Result.error(e.getMessage());
    }
//    //其他异常处理
//    @ExceptionHandler(Exception.class)
//    public Result exception(Exception e){
//        log.error("服务器异常：{}",e.getMessage());
//        return Result.error("服务器异常");
//    }

}
